package tt.dz.scheduletask.tasks;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tt.dz.dao.ext.charger.OmsChargerBespeakBillRecordDao;
import tt.dz.entity.charger.OmsChargerBespeakBillRecord;
import tt.dz.scheduletask.ScheduledTask;
import tt.dz.service.middleware.OmsBespeakService;
import tt.dz.service.middleware.OmsChargeService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class CancelReservationTask implements ScheduledTask
{
	private Log log = LogFactory.getLog(CancelReservationTask.class);

	private final int Valid_Period_Minute = 360;

//	private static int cnt = 0;

	@Autowired
	OmsChargerBespeakBillRecordDao omsChargerBespeakBillRecordDao;

	@Autowired
	OmsBespeakService omsBespeakService;

	@Override
	public void execute()
	{
//		if(cnt > 0)
//			return;
//		cnt ++;
		log.info("Cancel reservation task execute");
		try
		{
			StringBuffer sql = new StringBuffer();
			sql.append("     SELECT DISTINCT c.charger_id, c.protocol_type, c.protocol_version, b.port_no, b.user_pay_card, b.oms_msg_bespeak_jrnl ");
			sql.append("       FROM oms_charger c ");
			sql.append(" INNER JOIN oms_charger_bespeak_bill_record b ON c.charger_id = b.charger_id ");
			sql.append("      WHERE b.valid_flag = 1 AND c.valid_flag = 1 AND b.status = 2 ");
			sql.append("        AND b.oms_msg_bespeak_end_jrnl IS NULL ");
			sql.append("        AND SYSDATE() >= DATE_ADD(b.start_time, INTERVAL 360 MINUTE) ");// per 6 hour

			List<Map<String, Object>> list_expiredreservation = omsChargerBespeakBillRecordDao.findDataBySql(sql.toString());
			for(Map<String, Object> expiredreservation : list_expiredreservation)
			{
				log.info(String.format("Found expired reservation, start serial number is: %1$s", expiredreservation.get("oms_msg_bespeak_jrnl").toString()));
				try
				{
					Map<String, String> map = new HashMap<>();
					map.put("chargerId", expiredreservation.get("charger_id").toString());
					map.put("protocol_type", expiredreservation.get("protocol_type").toString());
					map.put("protocol_version", expiredreservation.get("protocol_version").toString());
					map.put("portNo", expiredreservation.get("port_no").toString());
					map.put("userCard", expiredreservation.get("user_pay_card").toString());
					map.put("bespeakStartSerialNumber", expiredreservation.get("oms_msg_bespeak_jrnl").toString());
					log.info(map);
					omsBespeakService.cancelBespeak(map);
//					log.info(map);
				}
				catch (Exception e)
				{
					log.error(e.getMessage(), e);
				}
			}
		}
		catch (Exception e)
		{
			log.error(e.getMessage(), e);
		}
	}
}
